package com.pat.web.controller;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jfinal.core.Controller;
import com.pat.web.ApiResponse;
import com.pat.web.NoNeedLogon;
import com.pat.web.model.PetCategory;

public class PetCategoryController extends Controller {

	@NoNeedLogon
	public void getPetCategory() {
		List<PetCategory> petCategories = PetCategory.dao.find("select * from pet_category order by sort");
		List<PetCategory> rootCategories = new ArrayList<PetCategory>();
		for (int i = 0; i < petCategories.size(); i++) {
			if (petCategories.get(i).getParentId().equals(petCategories.get(i).getId())) { // 根节点
				rootCategories.add(petCategories.get(i));
				petCategories.remove(petCategories.get(i));
			}
		}
		buildCategoryTree(rootCategories, petCategories);
		ApiResponse response = new ApiResponse();
		response.setData(rootCategories);
		response.setStatusCode("0000");
		renderJson(JSON.toJSONString(response, SerializerFeature.WriteDateUseDateFormat));
	}

	/**
	 * 生成所有节点
	 * 
	 * @param rootCategories
	 * @param petCategories
	 */
	public void buildCategoryTree(List<PetCategory> rootCategories, List<PetCategory> petCategories) {
		for (PetCategory rootCategory : rootCategories) {
			rootCategory.setNodes(new ArrayList<PetCategory>());
			for (PetCategory nodeCategory : petCategories) {
				if (nodeCategory.getParentId().equals(rootCategory.getId())) {
					rootCategory.getNodes().add(nodeCategory);
				}
			}
			buildCategoryTree(rootCategory.getNodes(), petCategories);
		}
	}
}
